<template>
  <div>
    <!--inline 是一个属性,指定表单的布局方式为行内表单布局,同一行显示表单项-->
    <el-form :model="queryForm" inline class="demo-form-inline" >
      <el-form-item label="姓名">
        <el-input placeholder="用户名" v-model="queryForm.username"></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input placeholder="手机号" v-model="queryForm.phoneNumber"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="queryForm.gender" placeholder="性别" class="longSelect">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="SearchIcon" @click="initGetUsersList()">查询</el-button>
        <el-button type="primary" @click="handleDialogValue()">新增</el-button>
        <el-button type="primary" @click="signOut()">退出登录</el-button>
      </el-form-item>
      <el-form-item>
         <el-button type="primary" @click="exportData">导出用户</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="username" label="姓名" width="100"></el-table-column>
      <el-table-column prop="phoneNumber" label="手机号" width="120"></el-table-column>
      <el-table-column prop="gender" label="性别" width="100"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="150"></el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="150"></el-table-column>
      <el-table-column prop="createUser" label="创建用户" width="100"></el-table-column>
      <el-table-column prop="updateUser" label="修改用户" width="100"></el-table-column>

     <!-- 状态列 -->
      <el-table-column prop="state" label="状态" width="150">
      <template v-slot="{ row }">
        <el-switch
          v-model="row.state"
          active-text="启用"
          inactive-text="禁用"
          @change="changeState(row)"
        ></el-switch>
      </template>
    </el-table-column>

        <!-- 操作列 -->
      <el-table-column label="操作" width="180">
        <template v-slot="{row}">
          <el-button size="small" type="primary" :icon="Edit"  @click="handleDialogValue(row)" />
          <el-button size="small" type="danger" :icon="Delete" @click="delUser(row)"/>
        </template>
      </el-table-column>
    </el-table>

  <el-pagination
      v-model:currentPage="queryForm.currentPage"
      :page-sizes="[5,10, 15, 20]"
      :page-size="queryForm.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  >
  </el-pagination>

</div>

<Dialog
    v-model="dialogVisible"
    :dialogTitle="dialogTitle"
    :dialogTableValue="dialogTableValue"
    @initUserList="initGetUsersList"
  />
</template>

<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { pageAPI, changeStateAPI, deleteUserAPI ,exportUserDataAPI } from '@/apis/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import Dialog from '@/views/User/components/dialog.vue'
import { useRouter } from 'vue-router'

//编程式路由导航
const router = useRouter();

const queryForm = ref({
  username: '',
  phoneNumber: '',
  gender: '',
  currentPage: 1,
  pageSize: 5,
});

 
const tableData = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogTableValue = ref({})
 
const initGetUsersList = async () => {
  const res = await pageAPI(queryForm.value)
  total.value = res.data.total
  tableData.value = res.data.records
}
initGetUsersList()
 
const handleSizeChange = (pageSize) => {
  queryForm.value.pageSize = pageSize
  initGetUsersList()
}
 
const handleCurrentChange = (currentPage) => {
  queryForm.value.currentPage = currentPage
  initGetUsersList()
}
 
const changeState = async (info) => {
  await changeStateAPI(info.id, info.state)
  ElMessage({
    message: '修改成功',
    type: 'success'
  })
}
 
const handleDialogValue = (info) => {
  dialogTitle.value = info ? '编辑用户' : '添加用户'
  dialogTableValue.value = info ? JSON.parse(JSON.stringify(info)) : {}
  dialogVisible.value = true
}
 
const delUser = (info) => {
  ElMessageBox.confirm('确定要删除用户?', 'Warning', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    type: 'warning'
  })
    .then(async () => {
      await deleteUserAPI(info.id)
      ElMessage({
        type: 'success',
        message: '删除已完成'
      })
      initGetUsersList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

//导出数据方法
const exportData = async () => {
  try {
    const params = new URLSearchParams();
    params.append('username', queryForm.value.username);
    params.append('gender', queryForm.value.gender);
    params.append('phoneNumber', queryForm.value.phoneNumber);

    //发送请求
    const response = await exportUserDataAPI(params);

     // 创建一个指向blob数据的URL
    const url = window.URL.createObjectURL(new Blob([response.data]));
 
    // 创建一个隐藏的a元素用于触发下载
    const link = document.createElement('a');
    link.href = url;
    // 设置下载文件的名称
    link.setAttribute('download', '用户数据.xlsx');
 
    // 将a元素添加到DOM中（虽然它不可见，但这是必需的）
    document.body.appendChild(link);
    // 触发点击事件以下载文件
    link.click();
 
    // 从DOM中移除a元素
    document.body.removeChild(link);
 
    // 释放URL对象
    window.URL.revokeObjectURL(url);


  } catch(error) {
    console.error('导出数据时发生错误:', error);
  }
}


//实现编程式路由导航
function signOut() {
  router.replace({
    name:'login'
  })
}

</script>
 
<style scoped>
.demo-form-inline {
  margin-bottom: 20px;
}
.el-table {
  margin-bottom: 20px;
}
.longSelect {
  width: 200px;
}
</style>